package com.example.girls.fragments

import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.girls.R
import com.example.girls.adapter.PHOTO_INDEX
import com.example.girls.adapter.PagerViewHolder
import com.example.girls.adapter.PhotoAdapter
import com.example.girls.viewModels.MyViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.fragment_photo.*
import kotlinx.android.synthetic.main.photo_cell.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.jar.Manifest

/**
 * 图片详情界面
 * implement viewpager2
 * */
private const val REQUEST_WRITE_EXTERNAL_STORAGE = 1
class PhotoFragment : Fragment() {
    // 提供全局的viewModel
    private val myViewModel by activityViewModels<MyViewModel>()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_photo, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val photoAdapter = PhotoAdapter() // 声明所需要的的适配器
        val photoList = myViewModel.photoListLiveData.value // 获取图片列表数据
        swipeRefreshPhoto.isEnabled = false // 其实这个也没啥用
        // 配置viewpager2
        viewpagerPhoto.apply {
            adapter = photoAdapter
            photoAdapter.submitList(photoList) // 提交列表数据
            val position = myViewModel.currentPosition
            myViewModel.perCurrentPosition = position
            Log.d("hello", "onActivityCreated: $position")
            // 回调图片滚动, 设置tag
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    myViewModel.currentPosition = position
                    val strTag = "${position + 1}/${photoList?.size}"
                    textViewTag.text = strTag
                }
            })
            // 显示之前浏览的图片
            setCurrentItem(position, false)
        }
        saveButton.setOnClickListener {
            if (Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(
                    requireContext(),
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                    arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_WRITE_EXTERNAL_STORAGE
                )
            } else {
                viewLifecycleOwner.lifecycleScope.launch {
                    savePhoto()
                }
            }
        }
    }

    private suspend fun savePhoto() {
        withContext(Dispatchers.IO) {
            val holder =
                (viewpagerPhoto[0] as RecyclerView).findViewHolderForAdapterPosition(viewpagerPhoto.currentItem) as PagerViewHolder
            val bitmap = holder.itemView.imageViewPhoto.drawable.toBitmap()
            val saveUri = requireContext().contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                ContentValues()
            )?: kotlin.run {
                Snackbar.make(requireView().findViewById(R.id.saveFragment), "存储失败", Snackbar.LENGTH_SHORT).show()
                return@withContext
            }

            requireContext().contentResolver.openOutputStream(saveUri).use {
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) {
                    MainScope().launch {
                        Snackbar.make(requireView().findViewById(R.id.saveFragment), "存储成功", Snackbar.LENGTH_SHORT).show()
                    }

                } else {
                    MainScope().launch {
                        Snackbar.make(requireView().findViewById(R.id.saveFragment), "存储失败", Snackbar.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_WRITE_EXTERNAL_STORAGE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    viewLifecycleOwner.lifecycleScope.launch {
                        savePhoto()
                    }
                } else {
                    Toast.makeText(requireActivity(), "权限获取失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}